package com.system.transfer.entity.dto;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;


import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.system.transfer.entity.Transfer;

public class TransferDTO {
     private String empName;
 	@DateTimeFormat(pattern="yyyy/MM/dd")  
     private Date startTime;
	@DateTimeFormat(pattern="yyyy/MM/dd")  
     private Date endTime;
     
	public String getEmpName() {
		return empName;
	}
	@JsonFormat(pattern = "yyyy/MM/dd",timezone="GMT+8")
	
	public Date getStartTime() {
		return startTime;
	}
	@JsonFormat(pattern = "yyyy/MM/dd",timezone="GMT+8")
	public Date getEndTime() {
		return endTime;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
		
	}
	
     
	public void setStartTime(Date startTime) {
		this.startTime = startTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	public static Specification<Transfer> getTransferPage(TransferDTO transferDTO){
		Specification<Transfer> spec = new Specification<Transfer>() {

			public Predicate toPredicate(Root<Transfer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				//1.Predicate查询条件集合
				 List<Predicate> list = new ArrayList<Predicate>(); 
				//2.根据 QueryDTO数据字段的值进行判断以及条件的组装
				 if(null != transferDTO) {
					
					 if(!StringUtils.isEmpty(transferDTO.getEmpName())) {
					 Predicate  p1 =  cb.like(root.join("employee").get("empName").as(String.class),"%"+ transferDTO.getEmpName()+ "%");
					 list.add(p1);
					
					 }
					 if(transferDTO.getStartTime()!=null) {
						 
						 Predicate  p2 = cb.greaterThanOrEqualTo(root.get("transferTime").as(Date.class), transferDTO.getStartTime());
						 list.add(p2);
					   }
					 if(transferDTO.getEndTime()!=null) {
						 
						 Predicate  p3= cb.lessThanOrEqualTo(root.get("transferTime").as(Date.class), transferDTO.getEndTime());
						 list.add(p3);
					   }
				 }
				
				 //3.Predicate查询条件集合的 size 创建对应的Predicate查询条件数组
				 Predicate[] p = new Predicate[list.size()];  
				 //4.CriteriaBuilder的and 函数组装 查询条件数组
				 return cb.and(list.toArray(p));  
			}
		};
		return spec;
		
	}
     
}